﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using Celeriq.Common;

namespace Celeriq.Utilities
{
	public static class UserDomain
	{
		public static List<SystemCredentials> LoadUserFile()
		{
			var userFile = ConfigurationSettings.GetUserFile();
			if (!File.Exists(userFile))
			{
				throw new Exception("There are no configured users.");
			}

			try
			{
				var retval = new List<SystemCredentials>();

				var xml = SecurityHelper.DecryptFromDisk(userFile);
				var document = new System.Xml.XmlDocument();
				document.LoadXml(xml);

				foreach (XmlNode node in document.DocumentElement.ChildNodes)
				{
					var name = XmlHelper.GetAttribute(node, "name", string.Empty);
					var password = XmlHelper.GetAttribute(node, "password", string.Empty);
					var id = XmlHelper.GetAttribute(node, "userid", Guid.NewGuid());
					retval.Add(new SystemCredentials() { UserName = name, Password = password, UserId = id });
				}
				return retval;
			}
			catch (Exception ex)
			{
				throw;
			}
		}

		public static void SaveUserFile(List<SystemCredentials> list)
		{
			try
			{
				var userFile = ConfigurationSettings.GetUserFile();

				//Create user file with default "root" user
				var document = new System.Xml.XmlDocument();
				document.LoadXml("<users></users>");

				foreach (var user in list)
				{
					var node = XmlHelper.AddElement(document.DocumentElement, "user");
					XmlHelper.AddAttribute(node, "name", user.UserName);
					XmlHelper.AddAttribute(node, "password", user.Password);
					XmlHelper.AddAttribute(node, "userid", user.UserId);
				}

				SecurityHelper.EncryptToDisk(userFile, document.OuterXml);
			}
			catch (Exception ex)
			{
				throw;
			}
		}

	}
}